var baidu = require('baidu-push');
var inherits = require('util').inherits;
var eventemitter = require('events').EventEmitter;
var debug = require('debug')('loopback:compoment:push:provider:baidu');

function BaiduProvider(pushSettings) {
    var settings = pushSettings || {};
    this.__settingupPushConnection(settings);
}

inherits(BaiduProvider, EventEmitter);

exports = module.exports = BaiduProvider;

BaiduProvider.prototype.__settingupPushConnection = function(settings) {
    var options = {};

    options.apiKey = settings.apiKey;
    options.secretKey = settings.secretKey;
    this._connection = baidu.createClient(options);
};

BaiduProvider.prototype.__createMessage  = function(notification) {
    var message = {};
    message.user_id = notification.userid;
    message.tag = notification.tag;
    message.push_type = notification.pushType;
    message.messages = [notification.message];
    message.msg_keys = [notification.messageKey];
    message.device_type = notification.deviceType;

    return message;
};


BaiduProvider.prototype.pushNotification = function (notification) {
    var self = this;
    var message = self.__createMessage(notification);

    self._connection.pushMessage(message, function(err, res) {
        if (err) {
            self.emit('error', err);
        }
    });
};

BaiduProvider.prototype.pushNotificationByGroup = function(useridlist, notification) {
    var self = this;
    var tag = notification.tag;
    var option = {};

    for (var userid in userlist) {
        if (userid == "") continue;
        option = {};
        option.user_id = userid;
        option.tag = tag;
        self._connection.setTag(option, function (err, res) {
            if (err) self.emit('error', err);
        });
    }

    self.pushNotification(notification);

    for (var userid in userlist) {
        if (userid == "") continue;
        option = {};
        option.user_id = userid;
        option.tag = tag;
        self._connection.deleteTag(option, function (err, res) {
            if (err) self.emit('error', err);
        });
    }
}


